FREE SHIPPING
to Singapore, Malaysia, Hongkong & Taiwan
* */ 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 < this.bodies.length; i++) { var b = this.bodies[i]; if(b.type === Body.DYNAMIC && !b.wantsToSleep) { return false; } } return true; }; /** * Make all bodies in the island sleep. * @method sleep */ Island.prototype.sleep = function () { for(var i = 0; i < this.bodies.length; i++) { var b = this.bodies[i]; b.sleep(); } return true; }; },{'../objects/Body': 31} ],59: [ function (_dereq_,module,exports) { var vec2 = _dereq_('../math/vec2'), Island = _dereq_('./Island'), IslandNode = _dereq_('./IslandNode'), IslandNodePool = _dereq_('./../utils/IslandNodePool'), IslandPool = _dereq_('./../utils/IslandPool'), Body = _dereq_('../objects/Body'); module.exports = IslandManager; /** * Splits the system of bodies and equations into independent islands * * @class IslandManager * @constructor * @param {Object} [options] * @extends Solver */ function IslandManager (options) { /** * @property nodePool * @type {IslandNodePool} */ this.nodePool = new IslandNodePool({ size: 16 }); /** * @property islandPool * @type {IslandPool} */ this.islandPool = new IslandPool({ size: 8 }); /** * The equations to split. Manually fill this array before running .split(). * @property {Array} equations */ this.equations = []; /** * The resulting {{#crossLink "Island"}}{{/crossLink}}s. * @property {Array} islands */ this.islands = []; /** * The resulting graph nodes. * @property {Array} nodes */ this.nodes = []; /** * The node queue, used when traversing the graph of nodes. * @private * @property {Array} queue */ this.queue = []; } /** * Get an unvisited node from a list of nodes. * @static * @method getUnvisitedNode * @param {Array} nodes * @return {IslandNode|boolean} The node if found, else false. */ IslandManager.getUnvisitedNode = function (nodes) { var Nnodes = nodes.length; for(var i = 0; i !== Nnodes; i++) { var node = nodes[i]; if(!node.visited && node.body.type === Body.DYNAMIC) { return node; } } return false; }; /** * Visit a node. * @method visit * @param {IslandNode} node * @param {Array} bds * @param {Array} eqs */ IslandManager.prototype.visit = function (node,bds,eqs) { bds.push(node.body); var Neqs = node.equations.length; for(var i = 0; i !== Neqs; i++) { var eq = node.equations[i]; if(eqs.indexOf(eq) === -1) { // Already added? eqs.push(eq); } } }; /** * Runs the search algorithm, starting at a root node. The resulting bodies and equations will be stored in the provided arrays. * @method bfs * @param {IslandNode} root The node to start from * @param {Array} bds An array to append resulting Bodies to. * @param {Array} eqs An array to append resulting Equations to. */ IslandManager.prototype.bfs = function (root,bds,eqs) { // Reset the visit queue var queue = this.queue; queue.length = 0; // Add root node to queue queue.push(root); root.visited = true; this.visit(root,bds,eqs); // Process all queued nodes while(queue.length) { // Get next node in the queue var node = queue.pop(); // Visit unvisited neighboring nodes var child; while((child = IslandManager.getUnvisitedNode(node.neighbors))) { child.visited = true; this.visit(child,bds,eqs); // Only visit the children of this node if it's dynamic if(child.body.type === Body.DYNAMIC) { queue.push(child); } } } }; /** * Split the world into independent islands. The result is stored in .islands. * @method split * @param {World} world * @return {Array} The generated islands */ IslandManager.prototype.split = function (world) { var bodies = world.bodies, nodes = this.nodes, equations = this.equations; // Move old nodes to the node pool while(nodes.length) { this.nodePool.release(nodes.pop()); } // Create needed nodes, reuse if possible for(var i = 0; i !== bodies.length; i++) { var node = this.nodePool.get(); node.body = bodies[i]; nodes.push(node); // if(this.nodePool.length){ // var node = this.nodePool.pop(); // node.reset(); // node.body = bodies[i]; // nodes.push(node); // } else { // nodes.push(new IslandNode(bodies[i])); // } } // Add connectivity data. Each equation connects 2 bodies. for(var k = 0; k !== equations.length; k++) { var eq = equations[k], i = bodies.indexOf(eq.bodyA), j = bodies.indexOf(eq.bodyB), ni = nodes[i], nj = nodes[j]; ni.neighbors.push(nj); nj.neighbors.push(ni); ni.equations.push(eq); nj.equations.push(eq); } // Move old islands to the island pool var islands = this.islands; for(var i = 0; i < islands.length; i++) { this.islandPool.release(islands[i]); } islands.length = 0; // Get islands var child; while((child = IslandManager.getUnvisitedNode(nodes))) { // Create new island var island = this.islandPool.get(); // Get all equations and bodies in this island this.bfs(child, island.bodies, island.equations); islands.push(island); } return islands; }; },{'../math/vec2': 30,'../objects/Body': 31,'./../utils/IslandNodePool': 50,'./../utils/IslandPool': 51,'./Island': 58,'./IslandNode': 60} ],60: [ function (_dereq_,module,exports) { module.exports = IslandNode; /** * Holds a body and keeps track of some additional properties needed for graph traversal. * @class IslandNode * @constructor * @param {Body} body */ function IslandNode (body) { /** * The body that is contained in this node. * @property {Body} body */ this.body = body; /** * Neighboring IslandNodes * @property {Array} neighbors */ this.neighbors = []; /** * Equations connected to this node. * @property {Array} equations */ this.equations = []; /** * If this node was visiting during the graph traversal. * @property visited * @type {Boolean} */ this.visited = false; } /** * Clean this node from bodies and equations. * @method reset */ IslandNode.prototype.reset = function () { this.equations.length = 0; this.neighbors.length = 0; this.visited = false; this.body = null; }; },{} ],61: [ function (_dereq_,module,exports) { var GSSolver = _dereq_('../solver/GSSolver'), Solver = _dereq_('../solver/Solver'), Ray = _dereq_('../collision/Ray'), vec2 = _dereq_('../math/vec2'), Circle = _dereq_('../shapes/Circle'), Convex = _dereq_('../shapes/Convex'), Line = _dereq_('../shapes/Line'), Plane = _dereq_('../shapes/Plane'), Capsule = _dereq_('../shapes/Capsule'), Particle = _dereq_('../shapes/Particle'), EventEmitter = _dereq_('../events/EventEmitter'), Body = _dereq_('../objects/Body'), Shape = _dereq_('../shapes/Shape'), LinearSpring = _dereq_('../objects/LinearSpring'), Material = _dereq_('../material/Material'), ContactMaterial = _dereq_('../material/ContactMaterial'), DistanceConstraint = _dereq_('../constraints/DistanceConstraint'), Constraint = _dereq_('../constraints/Constraint'), LockConstraint = _dereq_('../constraints/LockConstraint'), RevoluteConstraint = _dereq_('../constraints/RevoluteConstraint'), PrismaticConstraint = _dereq_('../constraints/PrismaticConstraint'), GearConstraint = _dereq_('../constraints/GearConstraint'), pkg = _dereq_('../../package.json'), Broadphase = _dereq_('../collision/Broadphase'), AABB = _dereq_('../collision/AABB'), SAPBroadphase = _dereq_('../collision/SAPBroadphase'), Narrowphase = _dereq_('../collision/Narrowphase'), Utils = _dereq_('../utils/Utils'), OverlapKeeper = _dereq_('../utils/OverlapKeeper'), IslandManager = _dereq_('./IslandManager'), RotationalSpring = _dereq_('../objects/RotationalSpring'); module.exports = World; /** * The dynamics world, where all bodies and constraints live. * * @class World * @constructor * @param {Object} [options] * @param {Solver} [options.solver] Defaults to GSSolver. * @param {Array} [options.gravity] Defaults to y=-9.78. * @param {Broadphase} [options.broadphase] Defaults to SAPBroadphase * @param {Boolean} [options.islandSplit=true] * @extends EventEmitter * * @example * var world = new World({ * gravity: [0, -10], * broadphase: new SAPBroadphase() * }); * world.addBody(new Body()); */ function World (options) { EventEmitter.apply(this); options = options || {}; /** * All springs in the world. To add a spring to the world, use {{#crossLink "World/addSpring:method"}}{{/crossLink}}. * * @property springs * @type {Array} */ this.springs = []; /** * All bodies in the world. To add a body to the world, use {{#crossLink "World/addBody:method"}}{{/crossLink}}. * @property {Array} bodies */ this.bodies = []; /** * Disabled body collision pairs. See {{#crossLink "World/disableBodyCollision:method"}}. * @private * @property {Array} disabledBodyCollisionPairs */ this.disabledBodyCollisionPairs = []; /** * The solver used to satisfy constraints and contacts. Default is {{#crossLink "GSSolver"}}{{/crossLink}}. * @property {Solver} solver */ this.solver = options.solver || new GSSolver(); /** * The narrowphase to use to generate contacts. * * @property narrowphase * @type {Narrowphase} */ this.narrowphase = new Narrowphase(this); /** * The island manager of this world. * @property {IslandManager} islandManager */ this.islandManager = new IslandManager(); /** * Gravity in the world. This is applied on all bodies in the beginning of each step(). * * @property gravity * @type {Array} */ this.gravity = vec2.fromValues(0, -9.78); if(options.gravity) { vec2.copy(this.gravity, options.gravity); } /** * Gravity to use when approximating the friction max force (mu*mass*gravity). * @property {Number} frictionGravity */ this.frictionGravity = vec2.length(this.gravity) || 10; /** * Set to true if you want .frictionGravity to be automatically set to the length of .gravity. * @property {Boolean} useWorldGravityAsFrictionGravity * @default true */ this.useWorldGravityAsFrictionGravity = true; /** * If the length of .gravity is zero, and .useWorldGravityAsFrictionGravity=true, then switch to using .frictionGravity for friction instead. This fallback is useful for gravityless games. * @property {Boolean} useFrictionGravityOnZeroGravity * @default true */ this.useFrictionGravityOnZeroGravity = true; /** * The broadphase algorithm to use. * * @property broadphase * @type {Broadphase} */ this.broadphase = options.broadphase || new SAPBroadphase(); this.broadphase.setWorld(this); /** * User-added constraints. * * @property constraints * @type {Array} */ this.constraints = []; /** * Dummy default material in the world, used in .defaultContactMaterial * @property {Material} defaultMaterial */ this.defaultMaterial = new Material(); /** * The default contact material to use, if no contact material was set for the colliding materials. * @property {ContactMaterial} defaultContactMaterial */ this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial,this.defaultMaterial); /** * For keeping track of what time step size we used last step * @property lastTimeStep * @type {Number} */ this.lastTimeStep = 1 / 60; /** * Enable to automatically apply spring forces each step. * @property applySpringForces * @type {Boolean} * @default true */ this.applySpringForces = true; /** * Enable to automatically apply body damping each step. * @property applyDamping * @type {Boolean} * @default true */ this.applyDamping = true; /** * Enable to automatically apply gravity each step. * @property applyGravity * @type {Boolean} * @default true */ this.applyGravity = true; /** * Enable/disable constraint solving in each step. * @property solveConstraints * @type {Boolean} * @default true */ this.solveConstraints = true; /** * The ContactMaterials added to the World. * @property contactMaterials * @type {Array} */ this.contactMaterials = []; /** * World time. * @property time * @type {Number} */ this.time = 0.0; this.accumulator = 0; /** * Is true during step(). * @property {Boolean} stepping */ this.stepping = false; /** * Bodies that are scheduled to be removed at the end of the step. * @property {Array} bodiesToBeRemoved * @private */ this.bodiesToBeRemoved = []; /** * Whether to enable island splitting. Island splitting can be an advantage for both precision and performance. See {{#crossLink "IslandManager"}}{{/crossLink}}. * @property {Boolean} islandSplit * @default true */ this.islandSplit = typeof(options.islandSplit) !== 'undefined' ? !!options.islandSplit : true; /** * Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. * @property emitImpactEvent * @type {Boolean} * @default true */ this.emitImpactEvent = true; // Id counters this._constraintIdCounter = 0; this._bodyIdCounter = 0; /** * Fired after the step(). * @event postStep */ this.postStepEvent = {type: 'postStep'}; /** * Fired when a body is added to the world. * @event addBody * @param {Body} body */ this.addBodyEvent = { type: 'addBody', body: null }; /** * Fired when a body is removed from the world. * @event removeBody * @param {Body} body */ this.removeBodyEvent = { type: 'removeBody', body: null }; /** * Fired when a spring is added to the world. * @event addSpring * @param {Spring} spring */ this.addSpringEvent = { type: 'addSpring', spring: null }; /** * Fired when a first contact is created between two bodies. This event is fired after the step has been done. * @event impact * @param {Body} bodyA * @param {Body} bodyB */ this.impactEvent = { type: 'impact', bodyA: null, bodyB: null, shapeA: null, shapeB: null, contactEquation: null }; /** * Fired after the Broadphase has collected collision pairs in the world. * Inside the event handler, you can modify the pairs array as you like, to * prevent collisions between objects that you don't want. * @event postBroadphase * @param {Array} pairs An array of collision pairs. If this array is [body1,body2,body3,body4], then the body pairs 1,2 and 3,4 would advance to narrowphase. */ this.postBroadphaseEvent = { type: 'postBroadphase', pairs: null }; /** * How to deactivate bodies during simulation. Possible modes are: {{#crossLink "World/NO_SLEEPING:property"}}World.NO_SLEEPING{{/crossLink}}, {{#crossLink "World/BODY_SLEEPING:property"}}World.BODY_SLEEPING{{/crossLink}} and {{#crossLink "World/ISLAND_SLEEPING:property"}}World.ISLAND_SLEEPING{{/crossLink}}. * If sleeping is enabled, you might need to {{#crossLink "Body/wakeUp:method"}}wake up{{/crossLink}} 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 {{#crossLink "Body/allowSleep:property"}}Body.allowSleep{{/crossLink}}. * @property sleepMode * @type {number} * @default World.NO_SLEEPING */ this.sleepMode = World.NO_SLEEPING; /** * Fired when two shapes starts start to overlap. Fired in the narrowphase, during step. * @event beginContact * @param {Shape} shapeA * @param {Shape} shapeB * @param {Body} bodyA * @param {Body} bodyB * @param {Array} contactEquations */ this.beginContactEvent = { type: 'beginContact', shapeA: null, shapeB: null, bodyA: null, bodyB: null, contactEquations: [] }; /** * Fired when two shapes stop overlapping, after the narrowphase (during step). * @event endContact * @param {Shape} shapeA * @param {Shape} shapeB * @param {Body} bodyA * @param {Body} bodyB */ this.endContactEvent = { type: 'endContact', shapeA: null, shapeB: null, bodyA: null, bodyB: null }; /** * Fired just before equations are added to the solver to be solved. Can be used to control what equations goes into the solver. * @event preSolve * @param {Array} contactEquations An array of contacts to be solved. * @param {Array} frictionEquations An array of friction equations to be solved. */ this.preSolveEvent = { type: 'preSolve', contactEquations: null, frictionEquations: null }; // For keeping track of overlapping shapes this.overlappingShapesLastState = { keys: [] }; this.overlappingShapesCurrentState = { keys: [] }; /** * @property {OverlapKeeper} overlapKeeper */ this.overlapKeeper = new OverlapKeeper(); } World.prototype = new Object(EventEmitter.prototype); World.prototype.constructor = World; /** * Never deactivate bodies. * @static * @property {number} NO_SLEEPING */ World.NO_SLEEPING = 1; /** * Deactivate individual bodies if they are sleepy. * @static * @property {number} BODY_SLEEPING */ World.BODY_SLEEPING = 2; /** * Deactivates bodies that are in contact, if all of them are sleepy. Note that you must enable {{#crossLink "World/islandSplit:property"}}.islandSplit{{/crossLink}} for this to work. * @static * @property {number} ISLAND_SLEEPING */ World.ISLAND_SLEEPING = 4; /** * Add a constraint to the simulation. * * @method addConstraint * @param {Constraint} constraint * @example * var constraint = new LockConstraint(bodyA, bodyB); * world.addConstraint(constraint); */ World.prototype.addConstraint = function (constraint) { this.constraints.push(constraint); }; /** * Add a ContactMaterial to the simulation. * @method addContactMaterial * @param {ContactMaterial} contactMaterial */ World.prototype.addContactMaterial = function (contactMaterial) { this.contactMaterials.push(contactMaterial); }; /** * Removes a contact material * * @method removeContactMaterial * @param {ContactMaterial} cm */ World.prototype.removeContactMaterial = function (cm) { var idx = this.contactMaterials.indexOf(cm); if(idx !== -1) { Utils.splice(this.contactMaterials,idx,1); } }; /** * Get a contact material given two materials * @method getContactMaterial * @param {Material} materialA * @param {Material} materialB * @return {ContactMaterial} The matching ContactMaterial, or false on fail. * @todo Use faster hash map to lookup from material id's */ World.prototype.getContactMaterial = function (materialA,materialB) { var cmats = this.contactMaterials; for(var i = 0, N = cmats.length; i !== N; i++) { var cm = cmats[i]; if((cm.materialA.id === materialA.id) && (cm.materialB.id === materialB.id) || (cm.materialA.id === materialB.id) && (cm.materialB.id === materialA.id)) { return cm; } } return false; }; /** * Removes a constraint * * @method removeConstraint * @param {Constraint} constraint */ World.prototype.removeConstraint = function (constraint) { var idx = this.constraints.indexOf(constraint); if(idx !== -1) { Utils.splice(this.constraints,idx,1); } }; var step_r = vec2.create(), step_runit = vec2.create(), step_u = vec2.create(), step_f = vec2.create(), step_fhMinv = vec2.create(), step_velodt = vec2.create(), step_mg = vec2.create(), xiw = vec2.fromValues(0,0), xjw = vec2.fromValues(0,0), zero = vec2.fromValues(0,0), interpvelo = vec2.fromValues(0,0); /** * Step the physics world forward in time. * * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take. * * @method step * @param {Number} dt The fixed time step size to use. * @param {Number} [timeSinceLastCalled=0] The time elapsed since the function was last called. * @param {Number} [maxSubSteps=10] Maximum number of fixed steps to take per function call. * * @example * // Simple fixed timestepping without interpolation * var fixedTimeStep = 1 / 60; * var world = new World(); * var body = new Body({ mass: 1 }); * world.addBody(body); * * function animate(){ * requestAnimationFrame(animate); * world.step(fixedTimeStep); * renderBody(body.position, body.angle); * } * * // Start animation loop * requestAnimationFrame(animate); * * @example * // Fixed timestepping with interpolation * var maxSubSteps = 10; * var lastTimeSeconds; * * function animate(t){ * requestAnimationFrame(animate); * timeSeconds = t / 1000; * lastTimeSeconds = lastTimeSeconds || timeSeconds; * * deltaTime = timeSeconds - lastTimeSeconds; * world.step(fixedTimeStep, deltaTime, maxSubSteps); * * renderBody(body.interpolatedPosition, body.interpolatedAngle); * } * * // Start animation loop * requestAnimationFrame(animate); * * @see http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World */ World.prototype.step = function (dt,timeSinceLastCalled,maxSubSteps) { maxSubSteps = maxSubSteps || 10; timeSinceLastCalled = timeSinceLastCalled || 0; if(timeSinceLastCalled === 0) { // Fixed, simple stepping this.internalStep(dt); // Increment time this.time += dt; } else { this.accumulator += timeSinceLastCalled; var substeps = 0; while (this.accumulator >= 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 < this.islandManager.islands.length; i++) { var island = this.islandManager.islands[i]; if(island.wantsToSleep()) { island.sleep(); } } } this.stepping = false; // Remove bodies that are scheduled for removal var bodiesToBeRemoved = this.bodiesToBeRemoved; for(var i = 0; i !== bodiesToBeRemoved.length; i++) { this.removeBody(bodiesToBeRemoved[i]); } bodiesToBeRemoved.length = 0; this.emit(this.postStepEvent); }; /** * Runs narrowphase for the shape pair i and j. * @method runNarrowphase * @param {Narrowphase} np * @param {Body} bi * @param {Shape} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Shape} sj * @param {Array} xj * @param {Number} aj * @param {Number} mu */ World.prototype.runNarrowphase = function (np,bi,si,xi,ai,bj,sj,xj,aj,cm,glen) { // Check collision groups and masks if(!((si.collisionGroup & sj.collisionMask) !== 0 && (sj.collisionGroup & si.collisionMask) !== 0)) { return; } // Get world position and angle of each shape vec2.rotate(xiw, xi, bi.angle); vec2.rotate(xjw, xj, bj.angle); vec2.add(xiw, xiw, bi.position); vec2.add(xjw, xjw, bj.position); var aiw = ai + bi.angle; var ajw = aj + bj.angle; np.enableFriction = cm.friction > 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 < np.contactEquations.length; i++) { e.contactEquations.push(np.contactEquations[i]); } } this.emit(e); } // divide the max friction force by the number of contacts if(typeof(numContacts) === 'number' && numFrictionEquations > 1) { // Why divide by 1? for(var i = np.frictionEquations.length - numFrictionEquations; i < np.frictionEquations.length; i++) { var f = np.frictionEquations[i]; f.setSlipForce(f.getSlipForce() / numFrictionEquations); } } } } }; /** * Add a spring to the simulation * * @method addSpring * @param {Spring} spring */ World.prototype.addSpring = function (spring) { this.springs.push(spring); var evt = this.addSpringEvent; evt.spring = spring; this.emit(evt); evt.spring = null; }; /** * Remove a spring * * @method removeSpring * @param {Spring} spring */ World.prototype.removeSpring = function (spring) { var idx = this.springs.indexOf(spring); if(idx !== -1) { Utils.splice(this.springs,idx,1); } }; /** * Add a body to the simulation * * @method addBody * @param {Body} body * * @example * var world = new World(), * body = new Body(); * world.addBody(body); * @todo What if this is done during step? */ World.prototype.addBody = function (body) { if(this.bodies.indexOf(body) === -1) { this.bodies.push(body); body.world = this; var evt = this.addBodyEvent; evt.body = body; this.emit(evt); evt.body = null; } }; /** * Remove a body from the simulation. If this method is called during step(), the body removal is scheduled to after the step. * * @method removeBody * @param {Body} body */ World.prototype.removeBody = function (body) { if(this.stepping) { this.bodiesToBeRemoved.push(body); } else { body.world = null; var idx = this.bodies.indexOf(body); if(idx !== -1) { Utils.splice(this.bodies,idx,1); this.removeBodyEvent.body = body; body.resetConstraintVelocity(); this.emit(this.removeBodyEvent); this.removeBodyEvent.body = null; } } }; /** * Get a body by its id. * @method getBodyById * @param {number} id * @return {Body} The body, or false if it was not found. */ World.prototype.getBodyById = function (id) { var bodies = this.bodies; for(var i = 0; i < bodies.length; i++) { var b = bodies[i]; if(b.id === id) { return b; } } return false; }; /** * Disable collision between two bodies * @method disableBodyCollision * @param {Body} bodyA * @param {Body} bodyB */ World.prototype.disableBodyCollision = function (bodyA,bodyB) { this.disabledBodyCollisionPairs.push(bodyA,bodyB); }; /** * Enable collisions between the given two bodies * @method enableBodyCollision * @param {Body} bodyA * @param {Body} bodyB */ World.prototype.enableBodyCollision = function (bodyA,bodyB) { var pairs = this.disabledBodyCollisionPairs; for(var i = 0; i < pairs.length; i += 2) { if((pairs[i] === bodyA && pairs[i + 1] === bodyB) || (pairs[i + 1] === bodyA && pairs[i] === bodyB)) { pairs.splice(i,2); return; } } }; /** * Resets the World, removes all bodies, constraints and springs. * * @method clear */ World.prototype.clear = function () { this.time = 0; // Remove all solver equations if(this.solver && this.solver.equations.length) { this.solver.removeAllEquations(); } // Remove all constraints var cs = this.constraints; for(var i = cs.length - 1; 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. * * 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 {@link #worldVisible} property. * * Objects that are not {@link #worldVisible} do not update their {@link #worldPosition}. * * @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; }; PIXI.DisplayObjectContainer.prototype.bringChildToTop = function (child) { if (child.parent !== this) { return; } return this.setChildIndex(child, this.children.length - 1); }; PIXI.DisplayObjectContainer.prototype.sendChildToBack = function (child) { if (child.parent !== this) { return; } return this.setChildIndex(child, 0); }; /** * 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 * * @name PIXI.DisplayObjectContainer#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 * * @name PIXI.DisplayObjectContainer#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. * * The worldTransform was calculated during the last render pass and is not updated when you call this method. * If this Sprite was just created and has never been rendered, you can call `updateTransform` on the Sprite itself. * If any of the Sprite's ancestors have been positioned, scaled, or rotated since the last render pass, * those changes have not yet have been applied to this Sprite's worldTransform. Call `updateTransform` * on the root-most (highest) ancestor that was changed. * * @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 < 1 || this.texture.crop.height < 1) { 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; cw |= 0; ch |= 0; if (!cw || !ch) { return; } 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; 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) // eslint-disable-line eqeqeq { 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 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 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) // eslint-disable-line eqeqeq { 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; 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 < j; i++) { this.renderSprite(children[i]); } this.flush(); }; /** * @method PIXI.WebGLFastSpriteBatch#renderSprite * @param sprite {Sprite} */ PIXI.WebGLFastSpriteBatch.prototype.renderSprite = function (sprite) { var texture = sprite.texture; var baseTexture = texture.baseTexture; var gl = this.gl; var textureIndex = sprite.texture.baseTexture.textureIndex; if (PIXI.WebGLRenderer.textureArray[textureIndex] != baseTexture && // eslint-disable-line eqeqeq baseTexture._glTextures[gl.id] && !sprite.texture.baseTexture.skipRender) { this.flush(); gl.activeTexture(gl.TEXTURE0 + textureIndex); gl.bindTexture(gl.TEXTURE_2D, baseTexture._glTextures[gl.id]); PIXI.WebGLRenderer.textureArray[textureIndex] = baseTexture; if(!sprite.texture._uvs) { return; } } // sprite = children[i]; if(!sprite.visible) { return; } var uvs, vertices = this.vertices, width, height, w0, w1, h0, h1, index; uvs = sprite.texture._uvs; width = sprite.texture.frame.width; height = sprite.texture.frame.height; if (sprite.texture.trim) { // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords.. var trim = sprite.texture.trim; w1 = trim.x - sprite.anchor.x * trim.width; w0 = w1 + sprite.texture.crop.width; h1 = trim.y - sprite.anchor.y * trim.height; h0 = h1 + sprite.texture.crop.height; } else { w0 = width * (1 - sprite.anchor.x); w1 = width * -sprite.anchor.x; h0 = height * (1 - sprite.anchor.y); h1 = height * -sprite.anchor.y; } index = this.currentBatchSize * 4 * this.vertSize; // xy vertices[index++] = w1; vertices[index++] = h1; vertices[index++] = sprite.position.x; vertices[index++] = sprite.position.y; // scale vertices[index++] = sprite.scale.x; vertices[index++] = sprite.scale.y; // rotation vertices[index++] = sprite.rotation; // uv vertices[index++] = uvs.x0; vertices[index++] = uvs.y1; // color vertices[index++] = sprite.alpha; // texture Index vertices[index++] = textureIndex; // xy vertices[index++] = w0; vertices[index++] = h1; vertices[index++] = sprite.position.x; vertices[index++] = sprite.position.y; // scale vertices[index++] = sprite.scale.x; vertices[index++] = sprite.scale.y; // rotation vertices[index++] = sprite.rotation; // uv vertices[index++] = uvs.x1; vertices[index++] = uvs.y1; // color vertices[index++] = sprite.alpha; // texture Index vertices[index++] = textureIndex; // xy vertices[index++] = w0; vertices[index++] = h0; vertices[index++] = sprite.position.x; vertices[index++] = sprite.position.y; // scale vertices[index++] = sprite.scale.x; vertices[index++] = sprite.scale.y; // rotation vertices[index++] = sprite.rotation; // uv vertices[index++] = uvs.x2; vertices[index++] = uvs.y2; // color vertices[index++] = sprite.alpha; // texture Index vertices[index++] = textureIndex; // xy vertices[index++] = w1; vertices[index++] = h0; vertices[index++] = sprite.position.x; vertices[index++] = sprite.position.y; // scale vertices[index++] = sprite.scale.x; vertices[index++] = sprite.scale.y; // rotation vertices[index++] = sprite.rotation; // uv vertices[index++] = uvs.x3; vertices[index++] = uvs.y3; // color vertices[index++] = sprite.alpha; // texture Index vertices[index++] = textureIndex; // increment the batchs this.currentBatchSize++; if(this.currentBatchSize >= 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; // eslint-disable-line camelcase 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; // eslint-disable-line camelcase filterBlock._previous_stencil_mgr = null; // eslint-disable-line camelcase 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 }); if (!this.context) { throw new Error('Failed to create a Canvas 2d context.'); } /** * 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 () { // 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.13.1', /** * 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} */ if (typeof AudioBufferSourceNode !== 'undefined') { if (!AudioBufferSourceNode.prototype.start) { AudioBufferSourceNode.prototype.start = AudioBufferSourceNode.prototype.noteGrainOn; } if (!AudioBufferSourceNode.prototype.stop) { AudioBufferSourceNode.prototype.stop = AudioBufferSourceNode.prototype.noteOff; } } // 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) { /* eslint-disable no-array-constructor */ var proto = new Array(); /* eslint-enable no-array-constructor */ 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) { // We include `varArgs` (unused) to ensure Object.assign.length === 2 Object.assign = function (target, varArgs) // eslint-disable-line no-unused-vars { '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 = { defaults: function (target, defaults) { var keys = Object.keys(defaults); for (var i = 0, len = keys.length; i < len; i++) { var key = keys[i]; if (target[key] === undefined) { target[key] = defaults[key]; } } return target; }, /** * 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.sqrt(Math.random()); out.x = this.centerX + 0.5 * r * Math.cos(p) * this.width; out.y = this.centerY + 0.5 * r * Math.sin(p) * this.height; 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; } } }); /** * The x coordinate of the center of the Ellipse. * @name Phaser.Ellipse#centerX * @property {number} centerX * @readonly */ Object.defineProperty(Phaser.Ellipse.prototype, 'centerX', { get: function () { return this.x + 0.5 * this.width; } }); /** * The y coordinate of the center of the Ellipse. * @name Phaser.Ellipse#centerY * @property {number} centerY * @readonly */ Object.defineProperty(Phaser.Ellipse.prototype, 'centerY', { get: function () { return this.y + 0.5 * this.height; } }); /** * 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 | c | tx | * | b | 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 = parseFloat(obj[xProp]); } if (obj[yProp]) { point.y = parseFloat(obj[yProp]); } return point; }; /** * Truncates the x and y values, removing any fractional parts. * * @method Phaser.Point.trunc * @static * @param {object} obj - The Point. * @return {object} The modified Point. */ Phaser.Point.trunc = function (obj) { obj.x = Phaser.Math.trunc(obj.x); obj.y = Phaser.Math.trunc(obj.y); return obj; }; /** * Tests a Point or Point-like object. * * @method Phaser.Point.isPoint * @static * @param {object} obj - The object to test. * @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 Phaser.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. */ 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; /** * A Rectangle with width and height zero. * @constant Phaser.EmptyRectangle * @type {Phaser.Rectangle} */ Phaser.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; } }); /** * The x position of the center of the Camera's viewport, relative to the top-left of the game canvas. * @name Phaser.Camera#centerX * @property {number} centerX * @readonly */ Object.defineProperty(Phaser.Camera.prototype, 'centerX', { get: function () { return (this.x + (0.5 * this.width)); } }); /** * The y position of the center of the Camera's viewport, relative to the top-left of the game canvas. * @name Phaser.Camera#centerY * @property {number} centerY * @readonly */ Object.defineProperty(Phaser.Camera.prototype, 'centerY', { get: function () { return (this.y + (0.5 * this.height)); } }); /** * @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* | | * | | | postUpdate*| | | * | | | 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} state - 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 postUpdate method is left empty for your own use. * It is called during the core game loop AFTER the Stage has had its postUpdate method called (including updateTransform). * It is called BEFORE Plugins have had their postUpdate methods called. * You don't need to call updateTransform yourself here unless Plugins need it. * * @method Phaser.State#postUpdate * @param {Phaser.Game} game */ postUpdate: 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.onPostUpdateCallback = state.postUpdate || 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 * @see Phaser.StateManager#preUpdate */ loadComplete: function () { if (this._created === false && this.onCreateCallback) { this._created = true; this.onCreateCallback.call(this.callbackContext, this.game); } else { this._created = true; } }, /** * @method Phaser.StateManager#loadUpdate * @protected * @see Phaser.Loader#finishedLoading */ loadUpdate: function () { if (this._created === false && this.onLoadUpdateCallback) { this.onLoadUpdateCallback.call(this.callbackContext, this.game); } }, /** * @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); } }, postUpdate: function () { if (this._created && this.onPostUpdateCallback) { this.onPostUpdateCallback.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.onPostUpdateCallback = 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